﻿using Dapper;
using System;
using BCEntity.Trading.Purchase.GoodsPurchaseItem;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.Purchase.GoodsPurchaseItem
{
    /// <summary>
    /// 商品采购项
    /// </summary>
    public class GoodsPurchaseItemData : IGoodsPurchaseItemData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM goodspurchaseitem";
        private const string QUERY = @"SELECT GoodsPurchaseItemId,VendorCategoryId,VendorCategoryName,VendorId,VendorName,PurchaseCount,PurchaseUnit,SaleGoodsCategoryId,
                                            CreateAdminId,CreateAdminName,CreateTime,UpdateTime,EditAdminId,EditAdminName,CategoryName,SaleGoodsId,GoodsName,SKU,
                                            SaleGoodsNormId,NormName,NormNo,HasTask
                                        FROM goodspurchaseitem";
        public GoodsPurchaseItemData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查商品采购项是否存在
        public async Task<bool> Exists(long goodsPurchaseItemId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseItemId=?GoodsPurchaseItemId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseItemId", goodsPurchaseItemId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加商品采购项
        public async Task<GoodsPurchaseItemEntity> Add(GoodsPurchaseItemEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("goodspurchaseitem", new string[] { "VendorCategoryId", "VendorCategoryName", "VendorId", "VendorName", "PurchaseCount",
                "PurchaseUnit", "SaleGoodsCategoryId", "CreateAdminId", "CreateAdminName", "CategoryName", "SaleGoodsId",
                "GoodsName", "SKU", "SaleGoodsNormId", "NormName", "NormNo"  });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseItemId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?VendorCategoryId", entity.VendorCategoryId, DbType.Int32, size: 11);
            parameters.Add("?VendorCategoryName", entity.VendorCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?VendorId", entity.VendorId, DbType.Int32, size: 11);
            parameters.Add("?VendorName", entity.VendorName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PurchaseCount", entity.PurchaseCount, DbType.Int32, size: 11);
            parameters.Add("?PurchaseUnit", entity.PurchaseUnit?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SaleGoodsNormId", entity.SaleGoodsNormId, DbType.Int64, size: 20);
            parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseItemEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改商品采购项
        public async Task<GoodsPurchaseItemEntity> Update(GoodsPurchaseItemEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("goodspurchaseitem", new string[] { "VendorCategoryId", "VendorCategoryName", "VendorId", "VendorName", "PurchaseCount",
                "PurchaseUnit", "SaleGoodsCategoryId", "EditAdminId", "EditAdminName", "CategoryName","SaleGoodsId", "GoodsName", "SKU", "SaleGoodsNormId", "NormName", "NormNo" }
                , new string[] { "GoodsPurchaseItemId" });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseItemId=?GoodsPurchaseItemId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseItemId", entity.GoodsPurchaseItemId, DbType.Int64, size: 20);
            parameters.Add("?VendorCategoryId", entity.VendorCategoryId, DbType.Int32, size: 11);
            parameters.Add("?VendorCategoryName", entity.VendorCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?VendorId", entity.VendorId, DbType.Int32, size: 11);
            parameters.Add("?VendorName", entity.VendorName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PurchaseCount", entity.PurchaseCount, DbType.Int32, size: 11);
            parameters.Add("?PurchaseUnit", entity.PurchaseUnit?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?SaleGoodsNormId", entity.SaleGoodsNormId, DbType.Int64, size: 20);
            parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseItemEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除商品采购项
        public async Task<bool> Delete(long goodsPurchaseItemId)
        {
            string sql = @"DELETE FROM goodspurchaseitem WHERE GoodsPurchaseItemId=?GoodsPurchaseItemId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseItemId", goodsPurchaseItemId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取商品采购项
        public async Task<GoodsPurchaseItemEntity> GetEntity(long goodsPurchaseItemId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseItemId=?GoodsPurchaseItemId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseItemId", goodsPurchaseItemId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<GoodsPurchaseItemEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购项列表
        public async Task<IEnumerable<GoodsPurchaseItemEntity>> GetList(long adminId, bool? hasTask)
        {
            string sql = string.Format("{0} WHERE CreateAdminId=?CreateAdminId AND HasTask=?HasTask", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CreateAdminId", adminId, DbType.Int64);
            parameters.Add("?HasTask", hasTask.HasValue && hasTask.Value ? true : false, DbType.Boolean);
            return await this.databaseContext.Slave.QueryAsync<GoodsPurchaseItemEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购项分页
        public async Task<(IEnumerable<GoodsPurchaseItemEntity>, int)> Query(string categoryName, string goodsName, string sku, string vendorName, string adminName, long? adminId,int? vendorId, bool? hasTask, 
            DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(categoryName))
            {
                wheres.Add("CategoryName LIKE CONCAT('%',CONCAT(?CategoryName,'%'))");
                parameters.Add("?CategoryName", categoryName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(goodsName))
            {
                wheres.Add("GoodsName LIKE CONCAT('%',CONCAT(?GoodsName,'%'))");
                parameters.Add("?GoodsName", goodsName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(sku))
            {
                wheres.Add("SKU LIKE CONCAT('%',CONCAT(?SKU,'%'))");
                parameters.Add("?SKU", sku?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(vendorName))
            {
                wheres.Add("VendorName LIKE CONCAT('%',CONCAT(?VendorName,'%'))");
                parameters.Add("?VendorName", vendorName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(adminName))
            {
                wheres.Add("CreateAdminName LIKE CONCAT('%',CONCAT(?CreateAdminName,'%'))");
                parameters.Add("?CreateAdminName", adminName?.Trim(), DbType.AnsiString);
            }
            if (adminId.HasValue)
            {
                wheres.Add("CreateAdminId=?CreateAdminId");
                parameters.Add("?CreateAdminId", adminId.Value, DbType.Int64);
            }
            if (vendorId.HasValue)
            {
                wheres.Add("VendorId=?VendorId");
                parameters.Add("?VendorId", vendorId.Value, DbType.Int32);
                if (!hasTask.HasValue)
                {
                    hasTask = false;
                }
            }
            if (hasTask.HasValue)
            {
                wheres.Add("HasTask=?HasTask");
                parameters.Add("?HasTask", hasTask.Value, DbType.Boolean);
            }

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM goodspurchaseitem {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<GoodsPurchaseItemEntity, int>(sql, parameters);
        }
        #endregion

        #region 修改已生成采购单
        public async Task<bool> UpdateCreatedTask(long goodsPurchaseItemId)
        {
            string sql = SqlCommands.GetUpdateSql("goodspurchaseitem", new string[] { "HasTask" }, new string[] { "GoodsPurchaseItemId" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HasTask", true, DbType.Boolean);
            parameters.Add("?GoodsPurchaseItemId", goodsPurchaseItemId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取采购项存在的供应商列表
        public async Task<IEnumerable<GoodsPurchaseItemEntity>> GetPurchaseItemsVendorList()
        {
            string sql = string.Format("SELECT VendorId,VendorName WHERE HasTask=0 GROUP BY VendorId", QUERY);
            return await this.databaseContext.Slave.QueryAsync<GoodsPurchaseItemEntity>(sql);
        }
        #endregion
    }
}



